package it.xiuxian.lib.utils;

import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.Shader;

import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;

import java.security.MessageDigest;

public class GlideRoundTransformCenterCrop extends CenterCrop{
    private static int radius = 10;

    public GlideRoundTransformCenterCrop(int radius) {
        GlideRoundTransformCenterCrop.radius = radius;
    }

    protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
        Bitmap transform = super.transform(pool, toTransform, toTransform.getWidth(), toTransform.getHeight());
        return roundCrop(pool, transform);
    }

    private static Bitmap roundCrop(BitmapPool pool, Bitmap source) {
        if (source == null) {
            return null;
        } else {
            Bitmap result = pool.get(source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_8888);
            if (result == null) {
                result = Bitmap.createBitmap(source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_8888);
            }

            Canvas canvas = new Canvas(result);
            Paint paint = new Paint();
            paint.setShader(new BitmapShader(source, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP));
            paint.setAntiAlias(true);
            RectF rectF = new RectF(0.0F, 0.0F, (float)source.getWidth(), (float)source.getHeight());
            canvas.drawRoundRect(rectF, (float)radius, (float)radius, paint);
            return result;
        }
    }

    public void updateDiskCacheKey(MessageDigest messageDigest) {
    }
}
